<template>
    <transition appear name="side_anime">
      <div id="board3">
        <el-header><h1>药物库存管理</h1></el-header>

        <!-- 查询 -->
        <div class="search">  
          <el-form :inline="true" :model="formInline" class="demo-form-inline">

            <el-form-item>
              <el-input v-model="formInline.medicineName" placeholder="药物名" clearable></el-input>
            </el-form-item>

            <el-form-item>
              <el-select v-model="formInline.medicalType" placeholder="药物类型" clearable>
                <el-option label="西药" value="西药"></el-option>
                <el-option label="中药" value="中药"></el-option>
                <el-option label="检查项目" value="检查项目"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-select v-model="formInline.medicineStatus" placeholder="药物状态" clearable>
                <el-option 
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="queryDrugInventory">查询</el-button>
              </el-form-item>
          </el-form>
        </div>

        <!-- 分割线 -->
        <el-divider></el-divider>
      
        <!-- 新增和批量删除按钮 -->
        <div class="btn">
          <el-button type="success" icon="el-icon-plus" size="small" @click="addMedicineVisible = true">新增药物</el-button>
          <!-- <el-button icon="el-icon-delete" type="danger" size="small" @click="removeRows()">批量删除</el-button> -->
        </div>

        <!-- 新增药物 -->
        <el-dialog
          title="添加药物"
          v-model="addMedicineVisible"
          width="30%">
          <el-form :model="addMedicineForm" ref="addMedicineForm" label-width="100px" class="demo-ruleForm" :rules="rules">
            <el-form-item label="药物名" prop="medicineName">
              <el-input v-model="addMedicineForm.medicineName" clearable></el-input>
            </el-form-item>
            <el-form-item label="药物类型" prop="medicalType">
              <el-select v-model="addMedicineForm.medicalType" placeholder="请选择" clearable style="width:100%">
                <el-option label="西药" value="西药"></el-option>
                <el-option label="中药" value="中药"></el-option>
                <el-option label="检查项目" value="检查项目"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item  label="药物单价"  prop="medicinePrice">
              <el-input v-model.number="addMedicineForm.medicinePrice" clearable></el-input>
            </el-form-item>
            <el-form-item label="原价" prop="medicineOriginalPrice">
              <el-input v-model.number="addMedicineForm.medicineOriginalPrice" clearable></el-input>
            </el-form-item>
            <el-form-item label="药物库存" prop="medicineStock">
              <el-input v-model.number="addMedicineForm.medicineStock" clearable></el-input>
            </el-form-item>
            <el-form-item label="规格" prop="specifications">
              <el-input v-model="addMedicineForm.specifications" clearable></el-input>
            </el-form-item>
            <el-form-item label="药物状态" prop="medicineStatus">
              <el-select v-model="addMedicineForm.medicineStatus" placeholder="请选择" clearable style="width:100%">
                <el-option 
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <span class="dialog-footer">
            <el-button @click="addMedicineVisible = false">取 消</el-button>
            <el-button type="primary" @click="addMedi('addMedicineForm')">确 定</el-button>
          </span>
        </el-dialog>
        
        <!-- 修改药物 -->
        <el-dialog
          title="修改药物"
          v-model="updateMedicineVisible"
          width="30%">
          <el-form :model="updateMedicineForm" ref="updateMedicineForm" label-width="100px" class="demo-ruleForm" :rules="rules">
            <el-form-item label="药物名" prop="medicineName">
              <el-input v-model="updateMedicineForm.medicineName" clearable></el-input>
            </el-form-item>
            <el-form-item label="药物类型" prop="medicalType">
              <el-select v-model="updateMedicineForm.medicalType" placeholder="请选择" clearable style="width:100%">
                <el-option label="西药" value="西药"></el-option>
                <el-option label="中药" value="中药"></el-option>
                <el-option label="检查项目" value="检查项目"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="药物单价" prop="medicinePrice">
              <el-input v-model.number="updateMedicineForm.medicinePrice" clearable></el-input>
            </el-form-item>
            <el-form-item label="原价" prop="medicineOriginalPrice">
              <el-input v-model.number="updateMedicineForm.medicineOriginalPrice" clearable></el-input>
            </el-form-item>
            <el-form-item label="药物库存" prop="medicineStock">
              <el-input v-model.number="updateMedicineForm.medicineStock" clearable></el-input>
            </el-form-item>
            <el-form-item label="规格" prop="specifications">
              <el-input v-model="updateMedicineForm.specifications" clearable></el-input>
            </el-form-item>
            <el-form-item label="药物状态" prop="medicineStatus">
              <el-select v-model="updateMedicineForm.medicineStatus" placeholder="请选择" clearable style="width:100%">
                <el-option 
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <span class="dialog-footer">
            <el-button @click="updateMedicineVisible = false">取 消</el-button>
            <el-button type="primary" @click="updateMedi('updateMedicineForm')">确 定</el-button>
          </span>
        </el-dialog>
        
        <!-- 药物数据列表 -->
        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">

            <!-- <el-table-column
            type="selection"
            width="55">
            </el-table-column> -->

            <el-table-column
            prop="medicineName"
            label="药物名"
            width="150">
            </el-table-column>

            <el-table-column
            prop="medicalType"
            label="药物类型"
            width="120">
            </el-table-column>

            <el-table-column
            prop="medicinePrice"
            label="药物单价"
            width="120">
            </el-table-column>

            <el-table-column
            prop="medicineOriginalPrice"
            label="药物原价"
            width="120">
            </el-table-column>

            <el-table-column
            prop="medicineStock"
            label="药物库存"
            width="120">
            </el-table-column>

            <el-table-column prop="specifications" label="药物规格" width="120">
            </el-table-column>

            <el-table-column
              prop="medicineStatus"
              label="药物状态" 
              width="120">
              <template #default="scope">
                <span v-if="scope.row.medicineStatus== 1">
                    <el-tag type="success">可用</el-tag>
                </span>
                <span v-if="scope.row.medicineStatus== 0">
                    <el-tag type="danger">不可用</el-tag>
                </span>
            </template>
            </el-table-column>

            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  :disabled="scope.row.medicineStatus == 0"
                  size="mini"
                  icon="el-icon-edit"
                  type="primary"
                  @click="handleUpdate(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  :disabled="scope.row.medicineStatus == 0"
                  size="mini"
                  type="danger"
                  icon="el-icon-switch-button"
                  @click="handleStop(scope.$index, scope.row)">停用药物</el-button>
              </template>
            </el-table-column>
        </el-table>

        <!-- <div style="margin-top: 20px">
          <el-button @click="toggleSelection()">取消选择</el-button>
        </div> -->

        <!-- 分页 -->
        <el-pagination
            class="pagination"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            v-model:currentPage="currentPage"
            v-model:pageSize="pageSize"
            :page-size="8"
            layout="total, prev, pager, next"
            :total=total>
        </el-pagination>

      </div>
    </transition>

</template>

<script>
import {medicineManageList} from '../../api/api'
import {addMedicine} from '../../api/api'
import {updateMedicine} from '../../api/api'
import {stopMedicine} from '../../api/api'

export default {
    inject:['reload'],
    
    data() {
      var checkNumber = (rule, value, callback) => {
        if (rule.required && !value) {
          return callback(new Error('不能为空'))
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入数字值'))
          } else {
            if (value <= 0) {
              callback(new Error('数值必须大于0'))
            } else {
              callback()
            }
          }
        }, 1000)
      }

      return {
        formInline: {
          medicineName: '',
          medicalType: '',
          medicineStatus: ''
        },

        options:[
          {
            value: '1',
            label: '可用',
          },
          {
            value: '0',
            label: '不可用',
          },
        ],
        value: '',

        tableData: [],

        addMedicineVisible:false,//添加药物显示隐藏
        addMedicineForm:{},//添加数据
        updateMedicineVisible:false,//修改药物显示隐藏
        updateMedicineForm:{},//修改数据
        currentPage:1,
        multipleSelection: [],
        pageSize:8,
        total:0,
        rules:{
          medicineName:{ required:true, message:'不能为空', trigger: 'blur'},
          medicalType:{ required:true, message:'不能为空', trigger: 'blur'},
          medicinePrice:{ required:true, validator:checkNumber, trigger: 'blur'},
          medicineOriginalPrice:{ required:true, validator:checkNumber, trigger: 'blur'},
          medicineStock:{ required:true, validator:checkNumber, trigger: 'blur'},
          specifications:{ required:true, message:'不能为空', trigger: 'blur'},
          medicineStatus:{ required:true, message:'不能为空', trigger: 'blur'}
        }
      }
    },

    mounted() {  //加载药物列表数据
      this.getMedicineList(1);
    },

    methods: {
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },

      //当每页数据条数发生改变的时候触发
      handleSizeChange(val) {
        // console.log(`每页 ${val} 条`)
        this.currentPage = 1;
        this.pageSize = val;
        this.getMedicineList();
      },
      //当页码发生改变的时候触发
      handleCurrentChange(val) {
        // console.log(`当前页: ${val}`)
        this.currentPage = val;
        this.getMedicineList(val);
      },

      getAllProData() {
        let medicineId = sessionStorage.getItem('medicineId')

        this.$depo.get({
          url: '',
          config: {
            params:{
              medicineID:medicineID
            }
          },
          cb: (res) => {
            console.log(res);
            this.tableData = res.data;
          }
        })
      },

      //获取药物列表
      getMedicineList(page) {
        let token = this.$store.state.medicalStaff.loginData.tokenValue
        console.log(token);
        let data = {
          'page':page,
          'size':8,
          medicineName:this.formInline.medicineName,
          medicalType:this.formInline.medicalType,
          medicineStatus:this.formInline.medicineStatus
          // 'medicineName':formInline.medicineName,
          // 'medicalType':formInline.medicalType,
          // 'medicineStatus':formInline.medicineStatus,
        }
        let header = {
          'satoken':token
        }
        console.log(data)
        console.log(this.options)
        medicineManageList(data,header).then(response =>{
          console.log('请求成功',response)
          if (response.ret == '0'){
            this.tableData = response.medicineIPage.records
            this.total = response.medicineIPage.total
          }else {
            this.$message({
              message:'暂无药物',
              type: 'error',
              showClose:true
          })
          }
        })
      },


      //添加药物
      addMedi(formName){
        let data = {
          medicineName:this.addMedicineForm.medicineName,
          medicalType:this.addMedicineForm.medicalType,
          medicinePrice:this.addMedicineForm.medicinePrice,
          medicineOriginalPrice:this.addMedicineForm.medicineOriginalPrice,
          medicineStock:this.addMedicineForm.medicineStock,
          specifications:this.addMedicineForm.specifications,
          medicineStatus:this.addMedicineForm.medicineStatus
        }
        let token = this.$store.state.medicalStaff.loginData.tokenValue
        let header = {
        'satoken':token
        }
        this.$refs[formName].validate((valid) => {  //开启校验
          if (valid) {   // 如果校验通过，请求接口，允许提交表单
            addMedicine(data,header).then(response => {
            console.log('请求成功',response)
            if (response.ret == '0'){
              this.$router.push('/homeview/medicineList')
              this.total++
              this.addMedicineVisible=false
              this.$message({
                message:'添加成功',
                type: 'success',
                showClose:true
              })
              this.reload()
            }else {
              this.$message({
                message:'添加失败',
                type: 'error',
                showClose:true
              })
            }
          })
          } else {   //校验不通过
            return false;
          }
        });

      },

      //修改药物
      handleUpdate(index,row){
        console.log(index,row);
        console.log(row.id);
        this.updateMedicineVisible=true,
        this.id=row.id,
        this.updateMedicineForm.medicineName=row.medicineName,
        this.updateMedicineForm.medicalType=row.medicalType,
        this.updateMedicineForm.medicinePrice=row.medicinePrice,
        this.updateMedicineForm.medicineOriginalPrice=row.medicineOriginalPrice,
        this.updateMedicineForm.medicineStock=row.medicineStock,
        this.updateMedicineForm.specifications=row.specifications
        this.updateMedicineForm.medicineStatus=row.medicineStatus.toString()
      },
      updateMedi(formName){
        let data = {
          id:this.id,
          medicineName:this.updateMedicineForm.medicineName,
          medicalType:this.updateMedicineForm.medicalType,
          medicinePrice:this.updateMedicineForm.medicinePrice,
          medicineOriginalPrice:this.updateMedicineForm.medicineOriginalPrice,
          medicineStock:this.updateMedicineForm.medicineStock,
          specifications:this.updateMedicineForm.specifications,
          medicineStatus:this.updateMedicineForm.medicineStatus
        }
        let token = this.$store.state.medicalStaff.loginData.tokenValue
        let header = {
        'satoken':token
        }
        this.$refs[formName].validate((valid) => {  //开启校验
          if (valid) {   // 如果校验通过，请求接口，允许提交表单
            updateMedicine(data,header).then(response => {
            console.log('请求成功',response)
            if (response.ret == '0'){
              this.$router.push('/homeview/medicineList')
              this.updateMedicineVisible=false
              this.$message({
                message:'修改成功',
                type: 'success',
                showClose:true
              })
              this.reload()
            }else {
              this.$message({
                message:'修改失败',
                type: 'error',
                showClose:true
              })
            }
          })
          } else {   //校验不通过
            return false;
          }
        });
        
      },

      //停用药物
      handleStop(index,row){
        let data = {
          id:row.id,
        }
        let token = this.$store.state.medicalStaff.loginData.tokenValue
        let header = {
        'satoken':token
        }
        // console.log(index,row);
        this.$confirm('此操作将永久停用该药物, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            stopMedicine(data,header).then(response => {
              console.log('请求成功',response)
              if (response.ret == '0'){
                this.$router.push('/homeview/medicineList')
                row.medicineStatus = 0
                this.$message({
                  message:'停用药物成功',
                  type: 'success',
                  showClose:true
                })
                this.reload()
              }else {
                this.$message({
                  message:'停用药物失败',
                  type: 'error',
                  showClose:true
                })
              }
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消停用药物',
            })
          })
      },

      //条件查询
      queryDrugInventory() {
        // this.$options.methods.getMedicineList(1)
        let token = this.$store.state.medicalStaff.loginData.tokenValue
        console.log(token);
        let data = {
          'page':this.currentPage,
          'size':8,
          medicineName:this.formInline.medicineName,
          medicalType:this.formInline.medicalType,
          medicineStatus:this.formInline.medicineStatus
        }
        let header = {
          'satoken':token
        }
        console.log(data)
        medicineManageList(data,header).then(response =>{
          console.log('请求成功',response)
          if (response.ret == '0'){
            this.tableData = response.medicineIPage.records
            this.total = response.medicineIPage.total
          }else {
            this.$message({
              message:'查询失败',
              type: 'error',
              showClose:true
          })
          }
        })
      },
    }
  }
</script>

<style scoped>
.side_anime-enter-from,.side_anime-leave-to{
  opacity: 1;
}

.side_anime-enter-active{
  animation: slideInLeft 1s;
}

.side_anime-leave-active{
  animation: slideOutLeft 1s;
}

#board3 .btn {
  text-align: left;
  margin: 10px 0 5px 0;
}
#board3 .search {
  text-align: left;
}
#board3 .pagination {
  margin-top: 30px;
}
</style>